{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "874a28b6",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch.onnx\n",
    "import torch.nn as nn\n",
    "import torch.optim as optim\n",
    "import torch.nn.functional as F\n",
    "from sklearn.datasets import load_iris\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.datasets import fetch_openml\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "# 加载鸢尾花数据集\n",
    "iris = load_iris()\n",
    "x, y = iris.data, iris.target\n",
    "\n",
    "# 划分训练集和测试集\n",
    "x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42)\n",
    "\n",
    "# 将数据转换为PyTorch的Tensor\n",
    "X_train_tensor = torch.tensor(x_train, dtype=torch.float32)\n",
    "y_train_tensor = torch.tensor(y_train, dtype=torch.long)\n",
    "X_test_tensor = torch.tensor(x_test, dtype=torch.float32)\n",
    "y_test_tensor = torch.tensor(y_test, dtype=torch.long)\n",
    "\n",
    "\n",
    "# 定义简单的神经网络模型\n",
    "class IrisModel(nn.Module):\n",
    "    def __init__(self):\n",
    "        super(IrisModel, self).__init__()\n",
    "        self.fc1 = nn.Linear(4, 8)\n",
    "        self.fc2 = nn.Linear(8, 3)  # 输入特征为4，输出类别为3\n",
    "\n",
    "    def forward(self, x):\n",
    "        x = F.relu(self.fc1(x))\n",
    "        x = F.log_softmax(self.fc2(x), dim=1)\n",
    "        return x\n",
    "\n",
    "\n",
    "# 初始化模型、损失函数和优化器\n",
    "model = IrisModel()\n",
    "criterion = nn.NLLLoss()\n",
    "optimizer = optim.Adam(model.parameters(), lr=0.01)\n",
    "\n",
    "# 训练模型\n",
    "for epoch in range(100):\n",
    "    optimizer.zero_grad()\n",
    "    output = model(X_train_tensor)\n",
    "    loss = criterion(output, y_train_tensor)\n",
    "    loss.backward()\n",
    "    optimizer.step()\n",
    "\n",
    "# 保存训练好的模型为PyTorch模型\n",
    "torch.save(model.state_dict(), 'iris_model.pth')\n",
    "\n",
    "# 模型评估\n",
    "model.eval()\n",
    "with torch.no_grad():\n",
    "    y_pred = model(X_test_tensor)\n",
    "    _, predicted = torch.max(y_pred, 1)\n",
    "    accuracy = (predicted == y_test_tensor).sum().item() / len(y_test_tensor)\n",
    "    print(f'Test Accuracy: {accuracy * 100:.2f}%')\n",
    "\n",
    "# 将模型转换为ONNX格式，并设置输入和输出的名称\n",
    "dummy_input = torch.randn(1, 4)  # 创建一个虚拟输入\n",
    "onnx_path = 'iris_model.onnx'\n",
    "input_names = ['input']\n",
    "output_names = ['output']\n",
    "torch.onnx.export(model, dummy_input, onnx_path, input_names=input_names, output_names=output_names)"
   ]
  },
  {
   "cell_type": "code",
   "outputs": [],
   "source": [
    "# 使用fetch_openml函数获取Iris数据集\n",
    "iris_data = fetch_openml(name='iris', version=1)\n",
    "\n",
    "# 创建特征矩阵和目标向量\n",
    "x = iris_data.data\n",
    "y = iris_data.target\n",
    "\n",
    "# 将特征矩阵和目标向量合并为一个DataFrame\n",
    "iris_df = pd.DataFrame(data=np.c_[x, y], columns=iris_data.feature_names + ['target'])\n",
    "\n",
    "# 保存数据集到本地CSV文件\n",
    "iris_df.to_csv('iris_dataset.csv', index=False)\n",
    "\n",
    "print(\"Iris数据集已保存到iris_dataset.csv文件中。\")\n"
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "715ae9c3c9b9e9ff",
   "execution_count": null
  }
 ],
 "metadata": {
  "kernelspec": {
   "name": "python3",
   "language": "python",
   "display_name": "Python 3 (ipykernel)"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
